using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Xml;
using System.Xml.XPath;

namespace Subkismet.Services.GoogleSafeBrowsing
{
    /// <summary>
    /// XML implementation for provider.
    /// </summary>
    public class XmlProvider : ProviderBase
    {
        #region Constructors

        public XmlProvider(string phishingFilePath, string malwareFilePath)
        {
            this.phishingFilePath = phishingFilePath;
            this.malwareFilePath = malwareFilePath;
        }

        #endregion

        #region Properties
        private string phishingFilePath;

        public string PhishingFilePath
        {
            get { return phishingFilePath; }
        }

        private string malwareFilePath;

        public string MalwareFilePath
        {
            get { return malwareFilePath; }
        }
        #endregion

        #region Public Methods
        public override void AddKey(string key, BlackListType listType)
        {
            string listPath = GetListTypePath(listType);

            XmlDocument document = new XmlDocument();
            document.Load(listPath);

            XPathNavigator navigator = document.CreateNavigator();

            navigator.MoveToChild("list", string.Empty);
            navigator.MoveToChild("keys", string.Empty);

            using (XmlWriter writer = navigator.PrependChild())
            {
                writer.WriteStartElement("key");
                writer.WriteValue(key);
                writer.WriteEndElement();
                writer.Close();
            }

            document.Save(listPath);
        }

        public override void RemoveKey(string key, BlackListType listType)
        {
            string listPath = GetListTypePath(listType);

            XmlDocument document = new XmlDocument();
            document.Load(listPath);

            XPathNavigator navigator = document.CreateNavigator();

            XPathNavigator nodeToDelete = navigator.SelectSingleNode(string.Format("list/keys/key[. ='{0}']", key));

            if (nodeToDelete != null)
            {
                nodeToDelete.DeleteSelf();
                document.Save(listPath);
            }
        }

        public override void AddKeys(List<Key> keys, BlackListType listType)
        {
            string listPath = GetListTypePath(listType);

            XmlDocument document = new XmlDocument();
            document.Load(listPath);

            XPathNavigator navigator = document.CreateNavigator();

            navigator.MoveToChild("list", string.Empty);
            navigator.MoveToChild("keys", string.Empty);

            using (XmlWriter writer = navigator.PrependChild())
            {
                foreach (Key key in keys)
                {
                    writer.WriteStartElement("key");
                    writer.WriteValue(key.Value);
                    writer.WriteEndElement();
                }
                writer.Close();
            }

            document.Save(listPath);
        }

        public override List<string> GetKeys(BlackListType listType)
        {
            string listPath = GetListTypePath(listType);

            XmlReader reader = XmlReader.Create(new MemoryStream(File.ReadAllBytes(listPath)));

            XPathDocument document = new XPathDocument(reader);
            XPathNavigator navigator = document.CreateNavigator();

            List<string> keys = new List<string>();

            foreach (XPathItem item in navigator.Select("/list/keys/key"))
            {
                keys.Add(item.Value);
            }

            return keys;
        }

        public override string GetLatestVersion(BlackListType listType)
        {
            string listPath = GetListTypePath(listType);

            XmlReader reader = XmlReader.Create(new MemoryStream(File.ReadAllBytes(listPath)));

            XPathDocument document = new XPathDocument(reader);
            XPathNavigator navigator = document.CreateNavigator();

            navigator.MoveToChild("list", string.Empty);
            navigator.MoveToAttribute("version", string.Empty);

            return navigator.Value;
        }

        public override void UpdateVersion(string updateVersion, BlackListType listType)
        {
            string listPath = GetListTypePath(listType);

            XmlDocument document = new XmlDocument();
            document.Load(listPath);

            XPathNavigator navigator = document.CreateNavigator();

            navigator.MoveToChild("list", string.Empty);
            navigator.MoveToAttribute("version", string.Empty);

            navigator.SetValue(updateVersion);


            document.Save(listPath);
        }

        public override void Clear(BlackListType listType)
        {
            File.Delete(GetListTypePath(listType));

            CreateNewFile(listType, this.GetListTypePath(listType));
        }
        #endregion

        #region Private Methods
        private string GetListTypePath(BlackListType listType)
        {
            if (listType == BlackListType.Malware)
            {
                CreateNewFile(BlackListType.Malware, this.MalwareFilePath);
                return this.MalwareFilePath;
            }
            else
            {
                CreateNewFile(BlackListType.Phishing, this.PhishingFilePath);
                return this.PhishingFilePath;
            }
        }

        private void CreateNewFile(BlackListType listType, string path)
        {
            if (!File.Exists(path))
            {
                File.WriteAllText(path, GetInitialXml(listType));
            }
        }

        private string GetInitialXml(BlackListType listType)
        {
            StringBuilder sb = new StringBuilder();

            StringWriterWithEncoding stringWriter = new StringWriterWithEncoding(sb, Encoding.UTF8);

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings);

            // Start document
            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("list");

            if (listType == BlackListType.Malware)
                xmlWriter.WriteAttributeString("type", "Malware");
            else
                xmlWriter.WriteAttributeString("type", "Phishing");

            xmlWriter.WriteAttributeString("version", "1.-1");

            xmlWriter.WriteStartElement("keys");
            xmlWriter.WriteEndElement();

            // End document
            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndDocument();

            xmlWriter.Flush();
            xmlWriter.Close();
            stringWriter.Flush();

            return stringWriter.ToString();
        }

        #endregion
    }

    internal class StringWriterWithEncoding : StringWriter
    {
        private Encoding myEncoding;

        public StringWriterWithEncoding(StringBuilder sb, Encoding encoding)
        {
            this.myEncoding = encoding;
        }

        public override Encoding Encoding
        { get { return this.myEncoding; } }
    }
}
